package com.qiantu.phone.ui.adapter;

import static android.app.Activity.RESULT_OK;

import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.hjq.base.BaseActivity;
import com.hjq.widget.layout.SettingBar;
import com.hjq.widget.swipelayout.SimpleSwipeListener;
import com.hjq.widget.swipelayout.SwipeLayout;
import com.hjq.widget.swipelayout.adapters.RecyclerSwipeAdapter;
import com.hjq.widget.view.SwitchButton;
import com.lxj.xpopup.XPopup;
import com.qiantu.api.db.LLSceneDBManager;
import com.qiantu.api.entity.SceneBean;
import com.qiantu.api.entity.SceneDetailBean;
import com.qiantu.api.entity.SceneInterruptModeBean;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.ui.activity.AddInterruptSceneActivity;
import com.qiantu.phone.ui.activity.AddTaskActivity;
import com.qiantu.phone.ui.activity.EditSceneBaseActivity;
import com.qiantu.phone.ui.activity.SceneInterruptModeActivity;
import com.qiantu.phone.ui.dialog.BottomDelayTimeDialog;
import com.qiantu.phone.ui.dialog.BottomInterruptSceneDialog;
import com.qiantu.phone.ui.dialog.BottomInterruptTimeDialog;

import org.jetbrains.annotations.NotNull;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class InterruptModeAdapter extends RecyclerSwipeAdapter {
    //不要修改，需要根据position
    protected int TOP_VIEW_TYPE = 0;
    protected int TASK_VIEW_TYPE = 1;
    protected int TASK_ADD_TYPE = 2;
    private SceneInterruptModeBean mInterruptModeBean;
    private int firstTaskItemMarginTop;
    private int lastTaskItemWhiteCoverMarginBottom;
    private int lastTaskItemContentMarginBottom;
    protected SceneInterruptModeActivity mAddInterruptSceneActivity;

    public InterruptModeAdapter(SceneInterruptModeActivity activity, SceneInterruptModeBean interruptModeBean){
        mAddInterruptSceneActivity = activity;
        mInterruptModeBean = interruptModeBean;
        firstTaskItemMarginTop = activity.getResources().getDimensionPixelSize(R.dimen.dp_m_12);
        lastTaskItemWhiteCoverMarginBottom = activity.getResources().getDimensionPixelSize(R.dimen.dp_12);
        lastTaskItemContentMarginBottom = activity.getResources().getDimensionPixelSize(R.dimen.dp_4);
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = null;
        if(viewType == TOP_VIEW_TYPE){
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_interrupt_mode_top, parent, false);
            return new TopItemViewHolder(view);
        } else if(viewType == TASK_ADD_TYPE){
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_empty_interrupt, parent, false);
            return new EmptyTaskItemViewHolder(view);
        } else {
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.interrupt_mode_scene_item, parent, false);
            return new TaskItemViewHolder(view);
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
        if(viewHolder instanceof InterruptModeAdapter.TopItemViewHolder){
            InterruptModeAdapter.TopItemViewHolder vh = (InterruptModeAdapter.TopItemViewHolder) viewHolder;
            vh.frequentlySwitch.setChecked(mInterruptModeBean.getEnable());
            vh.setTime.setRightText(mInterruptModeBean.getRunTimeSec()/3600 + "小时"+mInterruptModeBean.getRunTimeSec()%3600/60 + "分钟");
        } else if(viewHolder instanceof InterruptModeAdapter.EmptyTaskItemViewHolder){

        } else if (viewHolder instanceof InterruptModeAdapter.TaskItemViewHolder) {
            position = position - 2;
            RecyclerView.LayoutParams rl = (RecyclerView.LayoutParams) viewHolder.itemView.getLayoutParams();
            FrameLayout.LayoutParams whiteCoverLayoutLayoutParams = (FrameLayout.LayoutParams) ((InterruptModeAdapter.TaskItemViewHolder) viewHolder).whiteCoverLayout.getLayoutParams();
            FrameLayout.LayoutParams swipeLayoutLayoutParams = (FrameLayout.LayoutParams) ((InterruptModeAdapter.TaskItemViewHolder) viewHolder).swipeLayout.getLayoutParams();
            if(position == 0 && position == mInterruptModeBean.getRules().size() - 1){
                rl.topMargin = firstTaskItemMarginTop;
                whiteCoverLayoutLayoutParams.bottomMargin = lastTaskItemWhiteCoverMarginBottom;
                swipeLayoutLayoutParams.bottomMargin = lastTaskItemContentMarginBottom;
            }else if(position == 0){
                rl.topMargin = firstTaskItemMarginTop;
                whiteCoverLayoutLayoutParams.bottomMargin = 0;
                swipeLayoutLayoutParams.bottomMargin = 0;
            }else if(position == mInterruptModeBean.getRules().size() - 1){
                rl.topMargin = 0;
                whiteCoverLayoutLayoutParams.bottomMargin = lastTaskItemWhiteCoverMarginBottom;
                swipeLayoutLayoutParams.bottomMargin = lastTaskItemContentMarginBottom;
            }else{
                rl.topMargin = 0;
                whiteCoverLayoutLayoutParams.bottomMargin = 0;
                swipeLayoutLayoutParams.bottomMargin = 0;
            }
            SceneInterruptModeBean.InterruptSceneBean bean = mInterruptModeBean.getRules().get(position);
            InterruptModeAdapter.TaskItemViewHolder vh = (InterruptModeAdapter.TaskItemViewHolder) viewHolder;
            vh.ly.setTag(position);
            vh.deleteImage.setTag(position);
            vh.name.setText(bean.getSceneName());
            vh.subScene.setText(bean.getSubSceneName());
            vh.swipeLayout.addSwipeListener(new SimpleSwipeListener() {
                @Override
                public void onOpen(SwipeLayout layout) {
                    viewHolder.setIsRecyclable(false);
                }

                @Override
                public void onClose(SwipeLayout layout) {
                    viewHolder.setIsRecyclable(true);
                }
            });
            mItemManger.bind(viewHolder.itemView, position);//实现只展现一条列表项的侧滑区域
        }
    }

    @Override
    public int getItemCount() {
        int taskCount = 2;
        return mInterruptModeBean.getRules().size() + taskCount;
    }

    @Override
    public int getItemViewType(int position) {
        if (position == 0) {
            return TOP_VIEW_TYPE;
        } else if(position == 1){
            return TASK_ADD_TYPE;
        } else {
            return TASK_VIEW_TYPE;
        }
    }

    private BottomInterruptTimeDialog mBottomDelayTimeDialog;
    public void showBottomTimeDialog(int position){
        if (mBottomDelayTimeDialog == null) {
            mBottomDelayTimeDialog = new BottomInterruptTimeDialog(mAddInterruptSceneActivity);
            mBottomDelayTimeDialog.setDialogClickListener(new BottomInterruptTimeDialog.DialogClickListener() {
                @Override
                public void onConfirmClick(int longTime) {
                    mBottomDelayTimeDialog.dismiss();
                    mInterruptModeBean.setRunTimeSec(longTime);
                    notifyItemChanged(position);
                }
            });
            new XPopup.Builder(mAddInterruptSceneActivity)
                    .dismissOnBackPressed(true)
                    .enableDrag(true)
                    .asCustom(mBottomDelayTimeDialog);
        }
        mBottomDelayTimeDialog.setMillisecond(mInterruptModeBean.getRunTimeSec());
        mBottomDelayTimeDialog.show();
    }

    private BottomInterruptSceneDialog mBottomProtocolSwitchDialog;
    public void showProtocolDialog(int postion) {
        SceneInterruptModeBean.InterruptSceneBean bean = mInterruptModeBean.getRules().get(postion);
        SceneBean sceneBean = LLSceneDBManager.getInstance(mAddInterruptSceneActivity).getSceneBySerialNo(bean.getSceneSerialNo());
        sceneBean.setTemporary(LLSceneDBManager.getInstance(mAddInterruptSceneActivity).getScenesIntentBySerialNo(bean.getSceneSerialNo()));
        SceneBean subSceneBean = LLSceneDBManager.getInstance(mAddInterruptSceneActivity).getSceneBySerialNo(bean.getSubSceneSerialNo());
        if (mBottomProtocolSwitchDialog == null) {
            mBottomProtocolSwitchDialog = new BottomInterruptSceneDialog(mAddInterruptSceneActivity);
            mBottomProtocolSwitchDialog.setDialogClickListener(new BottomInterruptSceneDialog.DialogClickListener() {
                @Override
                public void onConfirmClick(SceneBean subScene) {
                    mBottomProtocolSwitchDialog.dismiss();
                    mInterruptModeBean.getRules().get(postion).setSceneSerialNo(sceneBean.getSceneSerialNo());
                    mInterruptModeBean.getRules().get(postion).setSubSceneSerialNo(subScene.getSceneSerialNo());
                    mInterruptModeBean.getRules().get(postion).setSceneName(sceneBean.getName());
                    mInterruptModeBean.getRules().get(postion).setSubSceneName(subScene.getName());
                    notifyDataSetChanged();
                }
            });
            new XPopup.Builder(mAddInterruptSceneActivity)
                    .dismissOnBackPressed(true)
                    .enableDrag(true)
                    .asCustom(mBottomProtocolSwitchDialog);
        }
        mBottomProtocolSwitchDialog.setScene(sceneBean);
        mBottomProtocolSwitchDialog.setSelected(subSceneBean);
        mBottomProtocolSwitchDialog.show();
    }
    @Override
    public long getItemId(int position) {
        return super.getItemId(position);
    }

    @Override
    public int getSwipeLayoutResourceId(int position) {
        return R.id.swipe_layout;
    }

    protected View.OnClickListener topBottomViewOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = null;
            switch (view.getId()) {
                case R.id.interrupt_mode_time:
                    showBottomTimeDialog(0);
                    break;
                case R.id.frequently_switch:
                    mInterruptModeBean.setEnable(!mInterruptModeBean.getEnable());
                    break;
                case R.id.add_task:
                    intent = new Intent(mAddInterruptSceneActivity, AddInterruptSceneActivity.class);
                    intent.putExtra("rules", (Serializable) mInterruptModeBean.getRules());

                    mAddInterruptSceneActivity.startActivityForResult(intent, new BaseActivity.OnActivityCallback() {
                        @Override
                        public void onActivityResult(int resultCode, @Nullable Intent data) {
                            if(resultCode == RESULT_OK){
                                List<SceneInterruptModeBean.InterruptSceneBean> beans= (List<SceneInterruptModeBean.InterruptSceneBean>) data.getSerializableExtra("selectSceneData");
                                if(mInterruptModeBean.getRules() == null){
                                    mInterruptModeBean.setRules(beans);
                                }else{
                                    mInterruptModeBean.getRules().addAll(beans);
                                }
                                notifyDatasetChanged();
                            }
                        }
                    });
                    break;

            }
        }
    };

    private final View.OnClickListener taskListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int position = (int) v.getTag();
            if (v.getId() == R.id.delete_image) {
                mInterruptModeBean.getRules().remove(position);
                notifyDataSetChanged();
                mItemManger.closeAllItems();
            }else if (v.getId() == R.id.ly) {
                if (mItemManger.isOpen(position)) {
                    mItemManger.closeItem(position);
                } else {
                    showProtocolDialog(position);
                }
            }
        }
    };

    private class TopItemViewHolder extends RecyclerView.ViewHolder {
        private SettingBar setTime;
        private SwitchButton frequentlySwitch;

        public TopItemViewHolder(@NonNull @NotNull View itemView) {
            super(itemView);
            setTime = itemView.findViewById(R.id.interrupt_mode_time);
            frequentlySwitch = itemView.findViewById(R.id.frequently_switch);

            setTime.setOnClickListener(topBottomViewOnClickListener);
            frequentlySwitch.setOnClickListener(topBottomViewOnClickListener);
        }
    }

    private class EmptyTaskItemViewHolder extends RecyclerView.ViewHolder {
        private ImageView addTask;

        public EmptyTaskItemViewHolder(@NonNull @NotNull View itemView) {
            super(itemView);
            addTask = itemView.findViewById(R.id.add_task);

            addTask.setOnClickListener(topBottomViewOnClickListener);
        }
    }

    private class TaskItemViewHolder extends RecyclerView.ViewHolder {

        public View whiteCoverLayout;
        public SwipeLayout swipeLayout;
        public LinearLayout seeLayout;
        public ImageView deleteImage;
        public ImageView icon;
        public TextView name;
        public TextView subScene;
        public LinearLayout valuesLy;
        public View ly;

        public TaskItemViewHolder(@NonNull @NotNull View itemView) {
            super(itemView);
            whiteCoverLayout = itemView.findViewById(R.id.white_cover_layout);
            swipeLayout = itemView.findViewById(R.id.swipe_layout);
            seeLayout = itemView.findViewById(R.id.see_layout);
            deleteImage = itemView.findViewById(R.id.delete_image);
            icon = itemView.findViewById(R.id.icon);
            name = itemView.findViewById(R.id.name);
            subScene = itemView.findViewById(R.id.sub_scene);
            valuesLy = itemView.findViewById(R.id.status_ly);
            ly = itemView.findViewById(R.id.ly);

            ly.setOnClickListener(taskListener);
            deleteImage.setOnClickListener(taskListener);
        }
    }



}
